package com.ruoyi.web.controller.alipay;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.entity.PayOrder;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.modules.domain.Contract;
import com.ruoyi.modules.service.ContractService;
import com.ruoyi.modules.service.PayOrderService;
import com.ruoyi.modules.service.SysUserPayOrderService;
import com.ruoyi.system.service.ISysUserOnlineService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.alipay.config.WebSocket;
import com.ruoyi.web.controller.alipay.domain.AliPay;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.alipay.api.msg.MsgConstants.SUCCESS;

/**
 * 支付接口
 * @author tlgen
 */
@RestController
@RequestMapping("/repay/data")
public class AlipayController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(RestController.class);

    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private SysUserPayOrderService userPayOrderService;

    @Autowired
    private ContractService contractService;

    private static final String body = "学生还款支付";

    // 支付宝商户号，登录www.yungouos.com-》支付宝-》我的支付 获取
    private static final String aliPayMch_id = "2088812886617069";

    // 微信商户号
    private static final String wxPayMch_id = "1604058231";

    // 支付宝商户密钥
    private static final String aliPayKey = "98771FBEDEEC4541BAB99647236711A8";

    // 微信商户密钥
    private static final String wxKey = "04C4EA8CC37241B4B4E736DA8A22C065";

    /**
     * 支付宝支付
     * @param totalFree 支付金额
     * @return
     */
    @PostMapping("/realPay")
    public AjaxResult realPay(@RequestParam("totalFree") String totalFree, @RequestParam("userId") Long userId) {
           AjaxResult ajax = AjaxResult.success();

           String result;

           // 回调地址
           String notify = "http://85s95wckrf.54http.tech/repay/data/payresult";

           String out_trade_no = System.currentTimeMillis() + "";

           // 支付宝扫码支付
           result = AliPay.nativePay(out_trade_no, totalFree, aliPayMch_id, body, "2", String.valueOf(userId), notify, aliPayKey);
           System.out.println("支付宝生成的二维码图片: " + result);

           ajax.put("msg", "支付宝生成的二维码图片地址");
           ajax.put("result", result);

       return ajax;
    }

    /**
     * 微信支付
     * @param totalFree 支付金额
     * @return
     */
    @PostMapping("/wxPay")
    public AjaxResult wxPay(@RequestParam("totalFree") String totalFree, @RequestParam("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();

        String result;

        // 回调地址
        String notify = "http://85s95wckrf.54http.tech/repay/data/wx/payresult";

        String out_trade_no = System.currentTimeMillis() + "";

        // 微信扫码支付
        result = AliPay.nativeWxPay(out_trade_no, totalFree, wxPayMch_id, body, "2", String.valueOf(userId), notify, wxKey);
        System.out.println("微信生成的二维码图片: " + result);

        ajax.put("msg", "微信生成的二维码图片地址");
        ajax.put("result", result);

        return ajax;
    }

    /**
     * 支付宝支付异步通知回调
     * @param code
     * @param orderNo
     * @param outTradeNo
     * @param payNo
     * @param money
     * @param mchId
     * @param payChannel
     * @param time
     * @param sign
     * @param request
     * @return
     */
    @PostMapping("/payresult")
    public String notifyUrl(@RequestParam("code") String code, @RequestParam("orderNo") String orderNo,
                                @RequestParam("outTradeNo") String outTradeNo, @RequestParam("payNo") String payNo,
                                @RequestParam("money")String money, @RequestParam("mchId") String mchId,
                                @RequestParam("payChannel") String payChannel, @RequestParam("time") String time,
                                @RequestParam("sign") String sign,  @RequestParam("attach") String attach, HttpServletRequest request) {

        code = request.getParameter("code");
        orderNo = request.getParameter("orderNo");
        outTradeNo = request.getParameter("outTradeNo");
        payNo = request.getParameter("payNo");
        mchId = request.getParameter("mchId");
        money = request.getParameter("money");
        payChannel = request.getParameter("payChannel");
        time = request.getParameter("time");
        attach = request.getParameter("attach");

        AjaxResult ajax = AjaxResult.success();
        System.out.println("已经收到支付宝服务器的回调通知!");
        ajax.put("code", code);
        ajax.put("outTradeNo", outTradeNo);
        ajax.put("money", money);
        ajax.put("payChannel", payChannel);
        ajax.put("time", time);

        PayOrder order = new PayOrder();
        order.setOrderNo(orderNo);
        order.setOutTradeNo(outTradeNo);
        order.setPayNo(payNo);
        order.setMoney(money);
        order.setBody(body);
        order.setMchid(mchId);
        order.setPayChannel(payChannel);
        order.setPayType(payChannel);
        order.setPayStatus(Integer.parseInt(code));
        order.setAddTime(time);
        order.setAttach(attach);
        order.setUserId(Long.parseLong(attach));
        payOrderService.insertPayOrder(order);

        // 更新用户与支付订单的中间表
        // 拿到最新的支付订单记录
        PayOrder payOrder = payOrderService.selectNewOneByUserIdAndNewAddTime(Long.parseLong(attach));
        System.out.println(payOrder.getPayId());
        System.out.println(Long.parseLong(attach));
        userPayOrderService.insertSysUserPayOrder(payOrder.getPayId(), Long.parseLong(attach));

        System.out.println("已经收到支付宝服务器的回调通知!");

        System.out.println("支付状态: " + code);
        // 后端主动向前端推送通知
        WebSocket.sendMessage(code);

        System.out.println("已经通过websocket主动向前端发送支付状态通知!");

        // 必须返回 SUCCESSS 大写字符串,且是com.alipay.api.msg包的MsgConstants中的SUCCESS常量
        return SUCCESS;
    }

    /**
     * 微信支付异步通知回调
     * @param code
     * @param orderNo
     * @param outTradeNo
     * @param payNo
     * @param money
     * @param mchId
     * @param payChannel
     * @param time
     * @param sign
     * @param request
     * @return
     */
    @PostMapping("/wx/payresult")
    public String notifyUrlWx(@RequestParam("code") String code, @RequestParam("orderNo") String orderNo,
                                @RequestParam("outTradeNo") String outTradeNo, @RequestParam("payNo") String payNo,
                                @RequestParam("money")String money, @RequestParam("mchId") String mchId,
                                @RequestParam("payChannel") String payChannel, @RequestParam("time") String time,
                                @RequestParam("sign") String sign, @RequestParam("attach") String attach, HttpServletRequest request) {

        code = request.getParameter("code");
        orderNo = request.getParameter("orderNo");
        outTradeNo = request.getParameter("outTradeNo");
        payNo = request.getParameter("payNo");
        mchId = request.getParameter("mchId");
        money = request.getParameter("money");
        payChannel = request.getParameter("payChannel");
        time = request.getParameter("time");
        attach = request.getParameter("attach");

        // 处理业务
        PayOrder order = new PayOrder();
        order.setOrderNo(orderNo);
        order.setOutTradeNo(outTradeNo);
        order.setPayNo(payNo);
        order.setMoney(money);
        order.setBody(body);
        order.setMchid(mchId);
        order.setPayChannel(payChannel);
        order.setPayType(payChannel);
        order.setPayStatus(Integer.parseInt(code));
        order.setAddTime(time);
        order.setAttach(attach);
        order.setUserId(Long.parseLong(attach));
        payOrderService.insertPayOrder(order);

        // 更新用户与支付订单的中间表
        // 拿到最新的支付订单记录
        PayOrder payOrder = payOrderService.selectNewOneByUserIdAndNewAddTime(Long.parseLong(attach));
        System.out.println(payOrder.getPayId());
        System.out.println(Long.parseLong(attach));
        userPayOrderService.insertSysUserPayOrder(payOrder.getPayId(), Long.parseLong(attach));

        System.out.println("已经收到微信服务器的回调通知!");

        System.out.println("支付状态: " + code);
        // 后端主动向前端推送通知
        WebSocket.sendMessage(code);

        System.out.println("已经通过websocket主动向前端发送支付状态通知!");

        // 必须返回 SUCCESSS 大写字符串,且是com.alipay.api.msg包的MsgConstants中的SUCCESS常量
        return SUCCESS;
    }


    /**
     * 查询所有学生还款信息
     * @param payOrder 订单对象
     * @return
     */
    @ApiOperation("查询学生还款信息")
    @GetMapping("/list")
    public TableDataInfo list(PayOrder payOrder)
    {
        startPage();
        List<PayOrder> list = payOrderService.selectPayOrderList(payOrder);
        return getDataTable(list);
    }

    /**
     * 根据当前用户userId和最新时间查询最新支付订单记录
     * @param userId 用户编号
     * @return
     */
    @ApiOperation("根据userId和最新时间查询最新支付订单记录")
    @GetMapping("/newOneByUserIdAndNewAddTime/{userId}")
    public AjaxResult selectNewOneByUserIdAndNewAddTime(@PathVariable Long userId)
    {
        return AjaxResult.success(payOrderService.selectNewOneByUserIdAndNewAddTime(userId));
    }

    /**
     * 根据当前用户名查询该用户的订单
     * @param userName 用户姓名
     * @return
     */
    @GetMapping("/selectPayOrderListBySysUser/{userName}")
    public AjaxResult selectPayOrderListBySysUser(@PathVariable String userName) {
        List<PayOrder> payOrders = payOrderService.selectPayOrderListBySysUser(userName);
        System.out.println(payOrders.size());
        AjaxResult ajax = AjaxResult.success();
        if (payOrders.size() == 1) {
            ajax.put("msg", "您还没有支付记录");
        } else {
            // lambda 循环累加求和 还款总金额
            Double totalMoney = payOrders.stream()
                    .mapToDouble(item -> Double.valueOf(item.getMoney()))
                    .sum();
            System.out.println("还款总金额: " + totalMoney);

            List<Contract> contracts = contractService.selectContractByName(userName);
            // lambda 循环累加求和 贷款的总金额
            Double creditMoney = contracts.stream()
                    .mapToDouble(item -> Double.valueOf(item.getFirstBorrowMoney()))
                    .sum();
            System.out.println("贷款总金额: " + creditMoney);

            ajax.put("creditMoney", creditMoney);
            ajax.put("totalMoney", totalMoney);
            ajax.put("data", payOrders);
        }
        return ajax;
    }

}
